from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.generics import CreateAPIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework_jwt.settings import api_settings
import logging

from .models import OAuthQQUser, OAuthWBUser
from .utils import OAuthQQ, OAuthWB
from .serializers import OAuthQQUserSerializer, OAuthWBUserSerializer
from carts.utils import merge_cart_cookie_to_redis

# Create your views here.

logger = logging.getLogger('django')


class QQAuthURLView(APIView):
    """
    获取QQ登录的url
    路由：/oauth/qq/authorization/?next=xxx
    """
    def get(self, request):

        next = request.query_params.get('next')
        oauth = OAuthQQ(state=next)
        qq_login_url = oauth.get_qq_login_url()
        return Response({'qq_login_url': qq_login_url})


class QQAuthUserView(CreateAPIView):
    """
    QQ登录的用户
    """
    serializer_class = OAuthQQUserSerializer

    def get(self, request):
        """获取openid  /oauth/qq/user/?code=xxx"""
        # 获取参数
        code = request.query_params.get('code')

        if not code:
            return Response({'message': '缺少code'}, status=status.HTTP_400_BAD_REQUEST)

        try:
            # 凭借code请求access_token
            oauth = OAuthQQ()
            access_token = oauth.get_access_token(code)

            # 凭借access_token请求openid
            openid = oauth.get_openid(access_token)
        except Exception:
            logger.error('获取openid失败')
            return Response({'message': '获取openid失败'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

        try:
            # 根据openid查询数据模型OAuthQQUser
            qq_user = OAuthQQUser.objects.get(openid=openid)
        except OAuthQQUser.DoesNotExist:
            # 如果没有QQ登录对象，生成access_token(处理openid)并返回
            access_token = oauth.generate_access_token(openid)
            return Response({'access_token': access_token})
        else:
            # 如果有QQ登录对象，返回JWT token
            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

            user = qq_user.user
            payload = jwt_payload_handler(user)
            token = jwt_encode_handler(payload)

            response = Response({
                'token': token,
                'username': user.username,
                'user_id': user.id
            })

            # 合并购物车
            response = merge_cart_cookie_to_redis(request, response, user)

            return response

    # def post(self):
    #     """绑定QQ身份  /oauth/qq/user/"""
    #     pass
    def post(self, request, *args, **kwargs):
        response = super().post(request, *args, **kwargs)

        user = self.user

        response = merge_cart_cookie_to_redis(request, response, user)

        return response


#  url(r'^sina/authorization/$', views.WBAuthURLView.as_view()),
class WBAuthURLView(APIView):
    """
    获取微博登录的url
    """
    def get(self, request):
        """
        提供用于微博登录的url
        """
        # 获取next参数
        next = request.query_params.get('next')
        # 拼接微博登录的网址
        oauth = OAuthWB(state=next)
        wb_login_url = oauth.get_wb_login_url()
        # 返回
        return Response({'wb_login_url': wb_login_url})


class WBAuthUserView(CreateAPIView):
    """
    微博登录的用户
    """
    serializer_class = OAuthWBUserSerializer

    def get(self, request):
        """获取access_token  /oauth/sina/user/?code=xxx"""
        # 获取code参数
        code = request.query_params.get('code')

        if not code:
            return Response({'message': '缺少code'}, status=status.HTTP_400_BAD_REQUEST)

        try:
            # 凭借code请求access_token
            oauth = OAuthWB()
            access_token = oauth.get_access_token(code).get('access_token')
            # print('access_token')

        except Exception:
            logger.error('获取access_token失败')
            return Response({'message': '获取access_token失败'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

        try:
            # 根据access_token查询数据模型OAuthWBUser
            wb_user = OAuthWBUser.objects.get(access_token=access_token)
        except OAuthWBUser.DoesNotExist:
            # 如果没有微博登录对象，生成access_token)并返回
            return Response({'access_token': access_token})
        else:
            # 如果有微博登录对象，返回JWT token
            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

            user = wb_user.user
            payload = jwt_payload_handler(user)
            token = jwt_encode_handler(payload)

            response = Response({
                'token': token,
                'username': user.username,
                'user_id': user.id
            })

            # 合并购物车
            response = merge_cart_cookie_to_redis(request, response, user)

            return response

    # def post(self):
    #     """绑定微博身份  /oauth/sina/user/"""
    #     pass
    def post(self, request, *args, **kwargs):
        response = super().post(request, *args, **kwargs)

        user = self.user

        response = merge_cart_cookie_to_redis(request, response, user)

        return response
